<template>
  <div class="dashboard-editor-container">
    <div v-if="showSuccess == showError">

      <el-tabs type="border-card">
        <el-tab-pane label="系统配置">
          <span slot="label" style="color: #333333"><i class="wshub wshub-bianji"></i>系统配置</span>
          <el-row :gutter="20">
            <el-col :sm="12" :xs="12" :lg="12" style="margin-top: 15px;">
<!--              <el-card class="box-card" style="width: 100%;min-height: 250px;" >-->
<!--                <div slot="header" class="clearfix">-->
<!--                  <span style="font-size: 15px;font-weight: 700;">WA管理</span>-->
<!--                </div>-->
<!--                <div class="text item">-->
<!--                  <el-col>-->
<!--                    <div>-->
<!--                      <span style="display: inline-block;font-size: 16px;width: 180px;">-->
<!--                        预启动实例-->
<!--                      </span>-->
<!--                      <el-select style="display: none;" v-model="preconfig.country" filterable placeholder="请选择任务目标国家">-->
<!--                        <el-option-->
<!--                          v-for="item in instanceCountry"-->
<!--                          :key="'preBoot'+item.country"-->
<!--                          :label="item.country+item.country_code+item.country_cn"-->
<!--                          :value="item.country_code">-->
<!--                          <span style="float: left">{{ item.country }}-{{item.country_cn}}(当前预启动:{{item.pre_boot}})</span>-->
<!--                          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.country_code }}</span>-->
<!--                        </el-option>-->
<!--                      </el-select>-->
<!--                    </div>-->
<!--                    <div style="display: none;">-->
<!--                      <span style="display: inline-block;font-size: 16px;width: 180px;">-->
<!--                        启动标签-->
<!--                      </span>-->
<!--                      <el-input v-model="preconfig.label" style="width: 220px;" placeholder="不填写则做目标国家任意任务"  ></el-input>-->
<!--                    </div>-->
<!--                    <div>-->
<!--                      <span style="display: inline-block;font-size: 16px;width: 180px;">-->
<!--                        启动次数-->
<!--                      </span>-->
<!--                      <el-input-number v-model="preconfig.num"  :min="-10000" @input="inputInstanceNum" :max="10000" label=""></el-input-number>-->
<!--                    </div>-->
<!--                    <div style="text-align: center;margin-top: 15px;">-->
<!--                      <el-button @click="preStart()" type="primary">预启动实例</el-button>-->
<!--                    </div>-->
<!--                  </el-col>-->
<!--                </div>-->
<!--              </el-card>-->
              <el-col :sm="24" :xs="24" :lg="24" style="padding: 0;margin: 0;margin-top: 15px;">
                <el-card class="box-card" style="width: 100%;min-height: 250px;" >
                  <div slot="header" class="clearfix">
                    <span style="font-size: 15px;font-weight: 700;">协议号入库</span>
                  </div>
<!--                  使用国:-->
                  <el-select style="display: none;" v-model="protocolData.use_country" filterable placeholder="请选择协议号使用国家">
                    <el-option
                      v-for="item in instanceCountry"
                      :key="'protocol_'+item.country"
                      :label="item.country+item.country_code+item.country_cn"
                      :value="item.country_code">
                      <span style="float: left">{{ item.country }}-{{item.country_cn}}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.country_code }}</span>
                    </el-option>
                  </el-select>
                  <div style="display: none;" >
                    <el-radio-group v-model="protocolData.add" style="margin-top: 15px;" >
                      <el-radio :label="1">补充国家</el-radio>
                      <el-radio :label="0">覆盖国家</el-radio>
                    </el-radio-group>
                    <el-alert
                      title="【补充国家】 原有协议号IN,现导入协议号为ID 则IN和ID的协议号混用"
                      type="info">
                    </el-alert>
                    <el-alert
                      title="【覆盖国家】 原有协议号IN,现导入协议号为ID 则只只用ID的协议号 IN将被排除配置"
                      type="info">
                    </el-alert>
                  </div>
                  <div>
                    <el-radio-group v-model="protocolData.platform" style="margin-top: 15px;" >
                      <el-radio :label="1">A类型(a,b,c参数类型)</el-radio>
                      <el-radio :label="2">B类型(me,keystore 参数类型)</el-radio>
                      <el-alert
                        title="不同协议号格式不同,若选择非对应的格式类型将导致协议号入库失败,若为3/6段号 则随任意选"
                        type="warning">
                      </el-alert>
                    </el-radio-group>
                  </div>
                  <div>
                    用途:
                    <el-radio-group v-model="protocolData.type" style="margin-top: 15px;" >
                      <el-radio :label="0">实例使用</el-radio>
<!--                      <el-radio :label="1">WA任务设备使用</el-radio>-->
<!--                      <el-radio :label="2">保留</el-radio>-->
                    </el-radio-group>
                  </div>
                  <div>
                    格式:
                    <el-radio-group v-model="protocolData.data_type" style="margin-top: 15px;" >
                      <el-radio :label="0">全段号</el-radio>
                      <el-radio :label="1">3/6段号</el-radio>
                    </el-radio-group>
                  </div>
<!--                  <div>-->
<!--                    协议模式:-->
<!--                    <el-radio-group v-model="protocolData.device_login" style="margin-top: 15px;" >-->
<!--                      <el-radio :label="1">A模式</el-radio>-->
<!--                      <el-radio :label="0">B模式</el-radio>-->
<!--                    </el-radio-group>-->
<!--                  </div>-->
                  <div class="text item" style="margin-top: 15px;">
                    <el-upload
                      class="upload-demo"
                      :action="action"
                      :limit="1"
                      ref="upload"
                      :headers="headers"
                      :file-list="fileList"
                      :auto-upload="true"
                      :data="protocolData"
                      :on-success="onSuccess"
                    >
                      <el-button size="small" type="primary">上传协议号文件</el-button>
                      <div slot="tip" class="el-upload__tip">只能上传协议号JSON数据的txt文件,导入立即生效</div>
                    </el-upload>
                  </div>
                </el-card>
              </el-col>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>
    <a-result
      status="success"
      title="保存成功"
      sub-title="TG配置成功保存,3秒后刷新显示"
      v-if="showSuccess"
    >
      <template #extra>
        <a-button key="console" @click="sreload" type="primary">
          立即刷新
        </a-button>
      </template>
    </a-result>

    <a-result
      status="error"
      title="保存失败"
      sub-title="配置保存失败,3秒后返回配置"
      v-if="showError"
    >
      <template #extra>
        <a-button key="console" @click="showError = false" type="primary">
          立即返回
        </a-button>
      </template>

      <div class="desc">
        <p style="font-size: 16px;">
          <strong>保存失败原因:</strong>
        </p>
        <p>
          <a-icon :style="{ color: 'red' }" type="close-circle" />
          <span style="font-size: 16px;color: red;">
            {{error}}
          </span>
        </p>
      </div>
    </a-result>

  </div>
</template>

<script>
import { getConfig,setConfig,testSplit,removeLock } from '@/api/config'
import {preBoot} from '@/api/whatsapp'
import { getAllCountry,brushLink } from '@/api/common'
import { getToken } from '@/utils/auth'
import { getAvailableCountry,buyProtocol,getRemaining } from '@/api/protocol'

export default {
  name: 'config',
  created() {
    getAllCountry({ext:1}).then(res => {
      if(res.code == 0){
        this.instanceCountry = res.data;
      }
    })
    this.getProtocolBuyCountryList();
  },
  data() {
    return {
      tableData:[],
      config:{
        wa_platform:'0',
        card_ignore:2,
        send_model:'0'
      },
      preconfig:{
        country:'PH',
        label:'',
        num:1
      },
      removeLock:{
        country:'',
        label:'',
      },
      brush:{
        country: '',
        num:1,
        url:'',
        follow:1
      },
      error:'',
      showSuccess:false,
      showError:false,
      instanceCountry:[],
      action:process.env.VUE_APP_BASE_API+'/protocol/addProtocol',
      headers: {sid:getToken()},
      fileList:[],
      protocolData:{
        use_country:'PH',
        add:1,
        platform:1,
        type:0,
        data_type:0,
        device_login:0
      },
      protocolBuyCountry:[],
      protocolRemaining:0,
      protocolBuy:{
        protocol_country:'',
        use_country:'',
        add:1,
        platform:1,
        num:1
      },
      total_num:1,
      task_split_channel: {
        start: 10000,
        channels: [
          { name: 'Wshub', type: 0, proportion: 0, min: 1 ,status:true},
          { name: 'SocialEpoch', type: 100, proportion: 0, min: 100,status:true },
          { name: 'WsSenders', type: 200, proportion: 0, min: 1000 ,status:true},
        ]
      },
      channel_configs: {
        channels: [
          { name: 'Wshub', type: 0, min: 1 ,max:100,status:true},
          { name: 'SocialEpoch', type: 100,min: 100,max:101,status:true },
          { name: 'WsSenders', type: 200,  min: 1000 ,max:10001,status:true},
          { name: 'Manual platform', type: 101,  min: 100000 ,max:100001,status:true}
        ]
      }
    }
  },
  methods: {
    getDataList() {
      const loading = this.$loading({
        lock: true,
        text: this.$t('v520.getting'),
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      getConfig().then(res => {
        loading.close()
        this.config = res.data;
        if(res.data.task_split_channel){
          this.task_split_channel = JSON.parse(res.data.task_split_channel);
        }else{
          this.task_split_channel.channels = [];
        }
        if(res.data.channel_configs){
          this.channel_configs = JSON.parse(res.data.channel_configs);
        }
      }).catch(err => {
        loading.close()
        console.log(err);
        this.$message.error('请求失败')
      })
    },
    getProtocolBuyCountryList() {
      // getAvailableCountry().then(res => {
      //   this.protocolBuyCountry = res.data;
      // }).catch(err => {
      //   this.$message.error('请求失败')
      // })
      //
      // getRemaining().then(res => {
      //   this.protocolRemaining = res.data.remaining;
      // });
    },
    save(){
      //校验平台配置
      let total = 0;
      try{
        if(this.task_split_channel.channels.length > 0){
          this.task_split_channel.channels.forEach((item) => {
            if(item.status != true){
              item.proportion = 0;
              return;
            }
            if(item.proportion == 0){
              item.status = false;
              return;
            }
            total += parseInt(item.proportion);
            if(total > 100){
              console.log(total);
              this.$notify.error({title:'保存失败',message:'比重配置错误'});
              throw new Error('fail');
            }
          })
        }
      }catch (e) {
        return;
      }

      if(this.task_split_channel.channels.length > 0 && total < 100){
        this.$notify.error({title:'保存失败',message:'比重配置错误,不足100%'});
        return;
      }


      try{
        this.channel_configs.channels.forEach((item) => {
          if(item.status != true){
              item.min = 0;
              item.max = 0;
              return;
          }
          if(item.min == 0){
              item.status = false;
              return;
          }

          if(item.min > item.max){
            this.$notify.error({title:'保存失败',message:'起点大于终点'});
            throw new Error('fail');
          }
        })
      }catch (e) {
        return;
      }

      // setConfig({config:this.config,channel_config:[]}).then(res => {
      setConfig({config:this.config,task_split_channel:this.task_split_channel,channel_configs:this.channel_configs}).then(res => {
          if(res.code == 0){
            this.showSuccess = true;
            let _this = this;
            setTimeout(function(){
              location.reload();
            },3000);
          }else{
            this.error = res.msg;
            this.showError = true;
            let _this = this;
            setTimeout(function(){
              if(_this.showError){
                _this.showError = false;
              }
            },3000);
          }
      });
    },
    preStart(){
      this.$confirm('此操作将会预启动任务目标国家为【'+this.preconfig.country+'】的'+this.preconfig.num+'台实例,是否确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        preBoot(this.preconfig).then(res => {
          if(res.code == 0){
            this.$message.success('预启动成功');
            this.preconfig.num = 1;
          }else{
            this.$message.error(res.msg);
          }
        });
      }).catch(() => {});
    },
    sreload(){
      location.reload();
    },
    onSuccess(response, file, fileList){
      if(response.code == 0){
        if(response.data.success != 0){
          this.$message.success(response.msg);

          if(response.data.not_me != 0 || response.data.phone_error != 0 || response.data.phone_repeat != 0){
            this.$notify.warning({title:'数据未全部成功导入',message:response.msg});
          }

        }else{
          this.$notify.error({title:'导入失败',message:'无成功的数据'});
          this.$message.error(response.msg);
        }
        fileList = [];
        this.fileList = [];
      }else{
        fileList = [];
        this.fileList = [];
        this.$message.error(response.msg);
      }
    },
    checkSwitch(row){
      if(row.status == false){
        if(row.hasOwnProperty('proportion')){
          row.proportion = 0;
        }

        if(row.hasOwnProperty('max')){
          row.min = 0;
          row.max = 0;
        }

      }
    },
    inputProportion(row){
      if(row.status == false){
        row.proportion = 0;
        this.$notify.error({title:'编辑失败',message:'未启用的通道无法配置比重'});
      }

      if(row.proportion < 0){
        row.proportion = -row.proportion;
      }

    },
    testS(){
      const h = this.$createElement;
      testSplit({num:this.total_num}).then(res => {
        if(res.code == 0){
          this.$msgbox({message:h('textarea',{style: { width: '100%',minHeight:'200px'}},res.msg), title:'已获得响应'});
        }else{
          this.$message.error(res.msg);
        }
      });
    },
    inputInstanceNum(){
      // if(this.preconfig.num <= 0){
      //   this.preconfig.num = 1;
      //   this.$notify.error({title:'值错误',message:'最少需要1实例'});
      // }
      if(this.preconfig.num > 10000){
        this.preconfig.num = 10000;
        this.$notify.error({title:'值错误',message:'预启动最高预启动10000次'});
      }
    },
    startBrush(){
      brushLink(this.brush).then(res =>{
        if(res.code == 0){
          this.$message.success('已启动刷链接');
        }else{
          this.$message.error(res.msg);
        }
      });
    },
    submitBuyProtocol(){
      const loading = this.$loading({
        lock: true,
        text: '购买中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      buyProtocol(this.protocolBuy).then(response => {
        loading.close();
        if(response.code == 0){
          if(response.data.success != 0){
            this.$message.success(response.msg);
            if(response.data.not_me != 0 || response.data.phone_error != 0 || response.data.phone_repeat != 0){
              this.$notify.warning({title:'购买数据成功',message:response.msg});
            }
          }else{
            this.$notify.error({title:'购买失败',message:'无成功的数据'});
            this.$message.error(response.msg);
          }
        }else{
          this.$message.error(response.msg);
        }
      }).catch(err => {
        loading.close();
        this.$message.error('发出购买请求失败,请稍后再试!');
      });

      this.getProtocolBuyCountryList();

    },
    submitLock(){
      removeLock(this.removeLock).then(res => {
        if(res.code == 0){
          this.$message.success('解除成功');
        }else{
          this.$message.error(res.msg);
        }
      }).catch(err =>{
        this.$message.error('请求失败,请重试!');
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  background-color: #FFF;
  min-height: 100vh;
  padding: 20px 20px 0px;

  .pan-info-roles {
    font-size: 12px;
    font-weight: 700;
    color: #333;
    display: block;
  }

  .info-container {
    position: relative;
    margin-left: 190px;
    height: 150px;
    line-height: 200px;

    .display_name {
      font-size: 48px;
      line-height: 48px;
      color: #212121;
      position: absolute;
      top: 25px;
    }
  }
}
</style>
